/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */
package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.IPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.StringPropertySelectionModel;
import org.apache.tapestry.form.LabeledPropertySelectionModel;
import org.apache.tapestry.form.BeanPropertySelectionModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.ICustomerService;
import com.crm.service.IContactService;
import com.crm.service.utils.ServiceUtils;
import com.crm.model.*;
import com.crm.web.util.Constants;
import com.crm.web.util.ListboxPropertySelectionModel;
import com.crm.web.util.PojoPropertySelectionModel;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class CustomerAll extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(CustomerAll.class);

    @InjectSpring("customerService")
    public abstract ICustomerService getCustomerServ();

    @InjectSpring("contactService")
    public abstract IContactService getContactServ();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectPage("CustomerInfo")
    public abstract CustomerInfo getCustomerInfoPage();

    @InjectPage("CustomerModify")
    public abstract CustomerModify getCustomerModifyPage();

    @Bean
    public abstract ValidationDelegate getDelegate();

    public abstract String getKeyword();

    public abstract String getCustName();

    public abstract String getCountry();

    public abstract String getWebsite();

    public abstract String getFieldSearch();

    public abstract Date getFromDate();

    public abstract Date getToDate();

    public abstract LProduct getProduct();

    public abstract LCustSource getSource();

    public abstract LCustLevel getLevel();

    public abstract String getUserSelected();

    @Persist
    public abstract boolean getAdvancedQuery();

    public abstract void setAdvancedQuery(boolean advanceQuery);

    public abstract int getCount();

    public abstract void setCount(int count);

    public IPropertySelectionModel getFieldSearchModel() {
        return new StringPropertySelectionModel(Constants.SEARCH_FIELD);
    }

    public IPropertySelectionModel getUserSelectionModel() {
        return new LabeledPropertySelectionModel(
                new PojoPropertySelectionModel(Constants.L_USER, "truename", "id"),
                Constants.SELECT_ALL);
    }

    public IPropertySelectionModel getSourceSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_SOURCE),
                Constants.SELECT_ALL);
    }

    public IPropertySelectionModel getLevelSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_LEVEL),
                Constants.SELECT_ALL);
    }

    public IPropertySelectionModel getProductSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_PRODUCT),
                Constants.SELECT_ALL);
    }

    public String getRecordCount() {
        return "共" + getCount() + "条记录";
    }

    public void pageBeginRender(PageEvent event) {
        if (getUserSession().getId() == null)
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
    }

    /**
     * 返回IBasicTableModel对象，实现分页查询只查询需要查询的记录
     *
     * @return
     */
//    public IBasicTableModel getModel(){
//        return new IBasicTableModel(){
//
//            private int rowCount=getAdminLoginService().getCount();
//
//            public Iterator getCurrentPageRows(int nFirst, int nPageSize, ITableColumn objSortColumn, boolean bSortOrder) {
//                String sortColumnId=objSortColumn==null?null:objSortColumn.getColumnName();
//                return getAdminLoginService().findAdmin(sortColumnId, bSortOrder, nFirst, nPageSize).iterator();
//            }
//
//            public int getRowCount() {
//                return rowCount;
//            }
//        };
//    }
    public List getEntries() {
        try {
            if (getAdvancedQuery()) {
                String[] s = new String[7];
                s[0] = getCustName() == null ? "" : getCustName().trim();
                s[1] = getCountry() == null ? "" : getCountry().trim();
                s[2] = getWebsite() == null ? "" : getWebsite().trim();
                s[3] = getProduct() == null ? "" : getProduct().getId();
                s[4] = getSource() == null ? "" : getSource().getId();
                s[5] = getLevel() == null ? "" : getLevel().getId();
                s[6] = getUserSelected() == null ? "" : getUserSelected();
                Date[] d = new Date[2];
                d[0] = getFromDate() == null ? ServiceUtils.MIN_DATE : getFromDate();
                d[1] = getToDate() == null ? ServiceUtils.MAX_DATE : getToDate();
                List list = getCustomerServ().getCustomers(getUserSession(), s, d);
                setCount(list.size());
                return list;
            }

            String keyword = getKeyword() == null ? "" : getKeyword().trim();
            String field = getFieldSearch() == null ? "" : getFieldSearch().trim();
            if (Constants.SEARCH_FIELD[3].equals(field)) {
                keyword = null == getProduct() ? "" : getProduct().getId();
            }
            List list = getCustomerServ().getCustomers(getUserSession(), new String[]{keyword, field}, null);
            setCount(list.size());
            return list;
        }
        catch (Exception e) {
            log.warn(getUserSession().getUsername() + ": System Error. " + e.getMessage());
            e.printStackTrace();
            return new ArrayList();
        }
    }

    public void searchByKeyword() {
    }

    public IPage newCustomer() {
        return getCustomerInfoPage();
    }

    public IPage onShowDetails(Customer customer) {
        log.info(getUserSession().getUsername() + ": check customer details [" + customer.toString() + "] ");

        try {
            CustomerModify page = getCustomerModifyPage();
            page.setCustomerInfo(customer);
            return page;
        }
        catch (Exception e) {
            e.printStackTrace();
            return getPage();
        }
    }

    public void deleteCustomer(Customer customer) {
        if (getContactServ().count(customer.getId()) > 0 ) {
            getDelegate().record("请先删除该客户的联系人记录", ValidationConstraint.CONSISTENCY);
        } else {
            getCustomerServ().delete(customer, getUserSession());
            getDelegate().record("用户【" + customer.getCustomerName() + "】已删除", ValidationConstraint.CONSISTENCY);
        }
    }

    public IPage showAdvanced() {
        setAdvancedQuery(true);
        return this;
    }

    public IPage showSimple() {
        setAdvancedQuery(false);
        return this;
    }

    public void doAdvanceQuery() {}    
}

